#include <QGraphicsDropShadowEffect>
#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "util/serverhelper.h"
#include "util/usermanager.h"
#include "util/messagebox.h"

#include <QDebug>

namespace WordMemory
{
    LoginWindow::LoginWindow(QWidget *parent)
        : QWidget(parent)
        , ui(new Ui::LoginWindow)
        , serverhelper(new ServerHelper(this))
    {
        ui->setupUi(this);

        ui->usernameEdit->setText("test");
        ui->passwordEdit->setText("1234");

        setupStyles();

        // 连接 ServerHelper 的登录信号
        connect(serverhelper, &ServerHelper::loginFinished,
            this, [this](bool success, const User &user, const QString &error) {
                if (success) {
                    UserManager::instance().setCurrentUser(user);
                    emit loginSuccess();
                    close();
                } else {
                    MessageBox::error(this, error);
                }
            });
    }

    void LoginWindow::setupStyles()
    {
        ui->usernameEdit->setStyleSheet(
            "QLineEdit { padding: 10px; border: 1px solid #d9d9d9; border-radius: 5px; font-size: 15px; background-color: #fafafa; }"
            "QLineEdit:hover { border: 1px solid #1890ff; }"
            "QLineEdit:focus { border: 1px solid #1890ff; background-color: #ffffff; }");
        ui->passwordEdit->setStyleSheet(
            "QLineEdit { padding: 10px; border: 1px solid #d9d9d9; border-radius: 5px; font-size: 15px; background-color: #fafafa; }"
            "QLineEdit:hover { border: 1px solid #1890ff; }"
            "QLineEdit:focus { border: 1px solid #1890ff; background-color: #ffffff; }");
        ui->loginButton->setStyleSheet(
            "QPushButton { background-color: #1890ff; color: white; font-size: 20px; padding: 10px; border-radius: 5px; border: none; min-height: 40px; }"
            "QPushButton:hover { background-color: #40a9ff; }"
            "QPushButton:pressed { background-color: #096dd9; }");

        // 添加阴影效果
        QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
        shadowEffect->setBlurRadius(12);
        shadowEffect->setXOffset(0);
        shadowEffect->setYOffset(4);
        shadowEffect->setColor(QColor(0, 0, 0, 0.1 * 255));
        ui->cardWidget->setGraphicsEffect(shadowEffect);
    }

    LoginWindow::~LoginWindow()
    {
        delete ui;
    }

    void LoginWindow::on_loginButton_clicked()
    {
        QString username = ui->usernameEdit->text();
        QString password = ui->passwordEdit->text();
        serverhelper->login(username, password);
    }
}
